package com.web.expspringboot.service.whuImpl;

import com.web.expspringboot.entity.ProductSt;
import com.web.expspringboot.mapper.ProductMapper;
import com.web.expspringboot.service.ProductService;
import com.web.expspringboot.service.PurchaseService;
import com.web.expspringboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Profile("whu")
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    UserService userService;

    @Autowired
    PurchaseService purchaseService;

    @Override
    public boolean uploadProduct(ProductSt product) {
        Long userId = userService.getSessionUserId();
        product.setOwnerId(userId);
        int res = productMapper.insertProduct(product);
        return res == 1;
    }

    @Override
    public boolean deleteProduct(long productId) {
        return productMapper.deleteProduct(productId) == 1;
    }

    @Override
    public int updateProduct(ProductSt product) {

        if(productMapper.updateProduct(product) == 1) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public ProductSt getProductById(long productId) {
        return productMapper.selectProductById(productId);
    }

    @Override
    public List<ProductSt> getAllProducts(int startIndex, int length) {
        return productMapper.selectAllProducts(startIndex, length);
    }

    @Override
    public List<ProductSt> getProductsByOwnerId(int startIndex, int length) {
        long ownerId = userService.getSessionUserId();

        return productMapper.selectProductsByOwnerId(ownerId, startIndex, length);
    }

    @Override
    public List<ProductSt> getProductsByTime(Date startTime, Date endTime) {
        String startString = String.format("%tF %<tT", startTime);
        String endString = String.format("%tF %<tT", endTime);
        return productMapper.selectProductsByTime(startString, endString);

    }

    @Override
    public int authProductOwner(long productId, long userId) {
        ProductSt product = productMapper.selectProductById(productId);
        if (product == null) {
            return 0;
        }
        if (product.getOwnerId() == userId) {
            return 1;
        }else {
            return 2;
        }
    }

    @Override
    public boolean updateProductStatus(long productId, int status){
        return productMapper.updateProductStatus(productId, status);
    }

    @Override
    public boolean resell(long productId) {
        if(purchaseService.deletePurchase(productId)){
            return productMapper.updateProductStatus(productId, 1);
        }
        return false;
    }

}
